package org.sdfc.query

import scala.collection.mutable.ArrayBuffer

import com.documentum.fc.client.IDfSession

import org.sdfc.model.dfc.collection.CollectionRow
import org.sdfc.model.dfc.collection.CollectionRows

/** View of a Query as a sequence of CollectionRow.
 *  <p>
 *  The point is to allow collection traversal to be done using
 *  sequence comprehension syntax.
 */
class PreparedRows (
  /** TypedQuery to be executed. */
  val query : TypedQuery,
  /** DFC session. */
  val session : IDfSession
) {
  
  /** Executes the prepared Query and applies the given function <code>rf</code>
   *  to each row of results available.
   */
  def foreach(rf : CollectionRow => Unit) {
    val coll = query.execute(session)
    try {
      new CollectionRows(coll).foreach(rf)
    }
    finally { coll.close() }
  }
  
  /** Executes the prepared Query and collects in an ArrayBuffer the results of applying
   *  the given function <code>rf</code> to each row of results available.
   */
  def map[T](rf : CollectionRow => T) : ArrayBuffer[T] = {
    val coll = query.execute(session)
    try {
      new CollectionRows(coll).map(rf)
    }
    finally { coll.close() }
  }
  
}
